package com.project.dao.impl;

import com.project.bean.SpeakBean;
import com.project.bean.UserBean;
import com.project.dao.ISpeakDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class SpeakDaoImpl extends BaseDao implements ISpeakDao {
    @Override
    public List<SpeakBean> findByProduct(int productId) {
        List<SpeakBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("SELECT s.*,u.`u_nickName` FROM t_user u,t_speak s WHERE u.`pk_userId`=s.`fk_userId` " +
                    "AND s.`fk_productId`=?");
            ps.setObject(1,productId);
            rs = ps.executeQuery();
            while(rs.next()){
                SpeakBean speak = new SpeakBean();
                speak.setId(rs.getInt("pk_speakId"));
                speak.setContent(rs.getString("s_content"));
                UserBean user = new UserBean();
                user.setNickName(rs.getString("u_nickName"));
                speak.setUser(user);
                list.add(speak);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }

        return list;
    }

    @Override
    public void addSpeak(SpeakBean speak) {
        this.setConnection();
        try {
            ps = con.prepareStatement("INSERT INTO t_speak(fk_userId,s_content,fk_productId) VALUES(?,?,?)");
            ps.setObject(1,speak.getUser().getId());
            ps.setObject(2,speak.getContent());
            ps.setObject(3,speak.getProduct().getId());

            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            this.closeConnection();
        }
    }
}
